package com.example.demo.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Author;
import com.example.demo.service.AuthorService;
import com.example.demo.util.PageUtil;
import com.example.demo.util.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/author")
@Api(value = "作者", tags = "作者")
public class Authorcontroller {

  @Autowired
  private AuthorService authorService;

  @GetMapping("/get_all")
  public R getAuthor() {
    return R.success(authorService.getAll());
  }

  @GetMapping("/find_author")
  @ApiOperation(value = "根据名称查找")
  public R findAuthor(
      @ApiParam(value = "名称查找") @RequestParam("name") String name,
      @RequestParam("page") int page,
      @RequestParam("limit") int limit) {

    PageUtil pageUtil = new PageUtil(page, limit);

    JSONObject data = new JSONObject();

    data.put("count", authorService.findByNameCount(name));
    data.put("authors", authorService.findByName(name, pageUtil));

    return R.success(data);
  }

  @PostMapping("/add")
  public R addAuthor(@RequestBody Author author) {
    boolean flag = authorService.add(author);

    if (flag) {
      return R.success("添加成功");
    } else {
      return R.fail("添加失败");
    }
  }

  @PostMapping("/update")
  public R updateAuthor(@RequestBody Author author) {
    boolean flag = authorService.update(author);

    if (flag) {
      return R.success("修改成功");
    } else {
      return R.fail("修改失败");
    }
  }

  @PostMapping("/delete")
  public R deleteAuthor(@RequestBody Map<String, String> body) {
    boolean flag = authorService.delete(Integer.parseInt(body.get("id")));

    if (flag) {
      return R.success("删除成功");
    } else {
      return R.fail("删除失败");
    }
  }
}
